package handler

import (
	"context"
	"user_rpc/global"
	"user_rpc/model"
	pb "user_rpc/proto"

	"golang.org/x/crypto/bcrypt"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
)

type UserServer struct {
	pb.UnimplementedUserServer
}

func (u *UserServer) CreateUser(ctx context.Context, req *pb.CreateUserRequest) (*pb.CreateUserResponse, error) {

	// 查询用户是否存在
	var user model.User
	result := global.DB.Where("username = ?", req.Username).First(&user)
	if result.RowsAffected > 0 {
		return nil, status.Errorf(codes.AlreadyExists, "用户已存在")
	}

	// 创建用户
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
	if err != nil {
		return nil, status.Errorf(codes.Internal, err.Error())
	}
	user.Password = string(hashedPassword)
	user.Username = req.Username
	result = global.DB.Create(&user)
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}
	return &pb.CreateUserResponse{
		Id: uint32(user.ID),
	}, nil
}

func (u *UserServer) GetUserByUsername(ctx context.Context, req *pb.GetUserByUsernameRequest) (*pb.UserResponse, error) {
	var user model.User
	result := global.DB.Where("username = ?", req.Username).First(&user)
	if result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "用户不存在")
	}
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}
	return &pb.UserResponse{
		Id:             uint32(user.ID),
		Username:       user.Username,
		HashedPassword: user.Password,
		Role:           uint32(user.Role),
	}, nil
}

func (u *UserServer) CheckPassword(ctx context.Context, req *pb.CheckPasswordRequest) (*pb.CheckPasswordResponse, error) {
	err := bcrypt.CompareHashAndPassword([]byte(req.HashedPassword), []byte(req.Password))
	if err != nil {
		return &pb.CheckPasswordResponse{Success: false}, nil
	}
	return &pb.CheckPasswordResponse{Success: true}, nil
}
func (u *UserServer) GetUserList(ctx context.Context, req *pb.PageInfo) (*pb.UserListResponse, error) {
	// 获取用户列表
	var users = make([]*model.User, 0)
	result := global.DB.Scopes(model.Paginate(int(req.PageNum), int(req.PageSize))).Find(&users)
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}
	resp := &pb.UserListResponse{}
	resp.Total = int32(result.RowsAffected)

	for _, user := range users {
		userInfo := &pb.UserResponse{
			Id:             uint32(user.ID),
			Username:       user.Username,
			HashedPassword: user.Password,
			Role:           uint32(user.Role),
		}
		resp.Users = append(resp.Users, userInfo)
	}

	return resp, nil
}

func (u *UserServer) UpdateUserRole(ctx context.Context, req *pb.UpdateUserRoleRequest) (*emptypb.Empty, error) {
	// 查询用户是否存在
	var user model.User
	result := global.DB.Where("username = ?", req.Username).First(&user)
	if result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "用户不存在")
	}

	// 更新用户信息
	user.Role = int(req.Role)
	result = global.DB.Model(&user).Select("Role").Updates(&user)
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}
	return &emptypb.Empty{}, nil
}
func (u *UserServer) UpdateUserName(ctx context.Context, req *pb.UpdateUserNameRequest) (*emptypb.Empty, error) {

	// 查询用户是否存在
	var user model.User
	result := global.DB.First(&user, req.Id)
	if result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "用户不存在")
	}

	// 更新用户信息
	user.Username = req.Username
	result = global.DB.Model(&user).Select("Username").Updates(&user)
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}
	return &emptypb.Empty{}, nil
}

func (u *UserServer) DeleteUser(ctx context.Context, req *pb.DeleteUserRequest) (*emptypb.Empty, error) {
	result := global.DB.Where("username = ?", req.Username).Delete(&model.User{})
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}
	return &emptypb.Empty{}, nil
}

func (u *UserServer) CreateApikey(ctx context.Context, req *pb.CreateApikeyRequest) (*pb.ApikeyResponse, error) {
	// 查询用户是否存在
	var user model.User
	result := global.DB.First(&user, req.Id)
	if result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "用户不存在")
	}

	// 更新用户信息
	user.Apikey = req.Apikey
	result = global.DB.Model(&user).Select("Apikey").Updates(&user)
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}
	return &pb.ApikeyResponse{
		Apikey: req.Apikey,
	}, nil
}

func (u *UserServer) GetApikey(ctx context.Context, req *pb.GetApikeyRequest) (*pb.ApikeyResponse, error) {
	// 查询用户是否存在
	var user model.User
	result := global.DB.First(&user, req.Id)
	if result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "用户不存在")
	}
	return &pb.ApikeyResponse{
		Apikey: user.Apikey,
	}, nil
}
